package aeolus.wind.spider.biz.dao;

import java.io.File;
import java.util.concurrent.TimeUnit;

import aeolus.wind.spider.biz.constants.Constants;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Durability;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;

public class BDBStore {

    private static final long DEFAULT_CACHE_SIZE = 40860000l;
    Environment               env                = null;

    public Environment getEnv() {
        return env;
    }

    public BDBStore(String bizName) {
        this(DEFAULT_CACHE_SIZE, bizName);
    }

    public BDBStore(long cacheSize, String bizName) {
        File envDir = new File(Constants.getPath() + bizName);
        if (!envDir.exists()) {
            envDir.mkdirs();
        }
        env = createEnv(envDir, cacheSize);
    }

    private Environment createEnv(File envDir, long cacheSize) throws DatabaseException {
        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setConfigParam(EnvironmentParams.ENV_RUN_EVICTOR.getName(), "false");
        envConfig.setConfigParam(EnvironmentParams.N_LOCK_TABLES.getName(), "5");
        envConfig.setAllowCreate(true);
        envConfig.setTransactional(true);
        envConfig.setTxnTimeout(10, TimeUnit.SECONDS);
        envConfig.setDurability(Durability.COMMIT_SYNC);
        if (cacheSize <= 0) {
            cacheSize = DEFAULT_CACHE_SIZE;
        }
        envConfig.setCacheSize(cacheSize); // cache Size 默认为5M
        return new Environment(envDir, envConfig);
    }

    public EntityStore createEntityStore(String storeName) throws DatabaseException {
        StoreConfig storeConfig = new StoreConfig();
        storeConfig.setAllowCreate(true);
        storeConfig.setTransactional(true);
        return new EntityStore(env, storeName, storeConfig);
    }

    /**
     * 同步数据
     */
    public void sync() {
        if (env != null) try {
            env.sync();
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭BDB
     */
    public void close() {
        try {
            if (env != null) env.close();
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }

    public Database openDatabase(File envDir) throws Exception {
        DatabaseConfig myDbConfig = new DatabaseConfig();
        // myDbConfig.setAllowCreate(true);
        Database db = env.openDatabase(null, envDir.getName(), myDbConfig);
        return db;
    }

    // public void printCursor() throws Exception {
    // db = primaryIndexStore.getDatabase();
    // String aKey = "myFirstKey";
    // String aData = "myFirstData";
    //
    // DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
    // DatabaseEntry theData = new DatabaseEntry(aData.getBytes("UTF-8"));
    // db.put(null, theKey, theData);
    // db.put(null, theKey, theData);
    //
    // Cursor myCursor = db.openCursor(null, null);
    // DatabaseEntry foundKey = new DatabaseEntry();
    // DatabaseEntry foundData = new DatabaseEntry();
    //
    // while (myCursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
    // String keyString = new String(foundKey.getData());
    // // ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(foundData.getData()));
    // // System.out.println(in.readObject().getClass());
    //
    // String dataString;
    // if (get(keyString.trim()) instanceof BdbStoreEntity) {
    // dataString = ((BdbStoreEntity) get(keyString.trim())).getContent();
    //
    // } else {
    // dataString = new String(foundData.getData());
    // }
    //
    // System.out.println(keyString.trim() + " | " + dataString);
    //
    // }
    // }

}
